<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="所属代理商" prop="agentId">
        <el-input v-model="queryParams.agentName" placeholder="请输入所属代理商" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNum">
        <el-input v-model="queryParams.orderNum" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备mac号" prop="sn">
        <el-input v-model="queryParams.mac" placeholder="请输入设备mac号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      
      <el-form-item label="变动类型" prop="changeType">
        <el-select v-model="queryParams.changeType" placeholder="请选择变动类型" clearable style="width:200px">
          <el-option v-for="dict in change_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="收益类型" prop="incomeType">
        <el-select v-model="queryParams.incomeType" placeholder="请选择收益类型" clearable style="width:200px">
          <el-option v-for="dict in income_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="钱包类型" prop="walletType">
        <el-select v-model="queryParams.walletType" placeholder="请选择钱包类型" clearable style="width:200px">
          <el-option v-for="dict in wallet_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="到账日期" prop="createTime">
        <!-- <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择创建时间">
        </el-date-picker> -->
        <el-date-picker v-model="createTime" type="datetimerange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['finance:bill:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['finance:bill:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['finance:bill:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['finance:bill:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属代理商" align="center" prop="agentName" v-if="columns[0].visible" />
      <el-table-column label="设备mac" align="center" prop="mac" v-if="columns[12].visible" width="200"/>
      <el-table-column label="到账日期" align="center" prop="timeId" v-if="columns[12].visible" width="150"/>
      <el-table-column label="订单号" align="center" prop="orderNum" v-if="columns[1].visible" width="200" />
      <el-table-column label="余额" align="center" prop="amount" v-if="columns[2].visible"  />
      <el-table-column label="变动前金额" align="center" prop="beforeAmount" v-if="columns[3].visible" width="100"/>
      <el-table-column label="变动后金额" align="center" prop="afterAmount" v-if="columns[4].visible" width="100"/>
      <el-table-column label="变动类型" align="center" prop="changeType" v-if="columns[5].visible">
        <template #default="scope">
          <dict-tag :options="change_type" :value="scope.row.changeType" />
        </template>
      </el-table-column>
      <el-table-column label="收益类型" align="center" prop="incomeType" v-if="columns[6].visible">
        <template #default="scope">
          <dict-tag :options="income_type" :value="scope.row.incomeType" />
        </template>
      </el-table-column>
      <el-table-column label="分成金额" align="center" prop="divideAmount" v-if="columns[7].visible" />
      <el-table-column label="云商到账金额" align="center" prop="protoAmount" v-if="columns[8].visible"  width="150"/>
      <el-table-column label="钱包类型" align="center" prop="walletType" v-if="columns[9].visible">
        <template #default="scope">
          <dict-tag :options="wallet_type" :value="scope.row.walletType" />
        </template>
      </el-table-column>
      <el-table-column label="分润比例" align="center" prop="ratio" v-if="columns[10].visible" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[11].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
     
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改账户订单对话框 -->
    <el-dialog :title="title" v-model="open" :width="dialogWidth" append-to-body>
      <el-form ref="billRef" :model="form" :rules="rules">
        <el-row :gutter="20">

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="所属代理商" prop="agentId">
              <el-input v-model="form.agentId" placeholder="请输入所属代理商" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="订单号" prop="orderNum">
              <el-input v-model="form.orderNum" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="余额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入余额" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="变动前金额" prop="beforeAmount">
              <el-input v-model="form.beforeAmount" placeholder="请输入变动前金额" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="变动后金额" prop="afterAmount">
              <el-input v-model="form.afterAmount" placeholder="请输入变动后金额" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="变动类型" prop="changeType">
              <el-radio-group v-model="form.changeType">
                <el-radio v-for="dict in change_type" :key="dict.value"
                  :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="收益类型" prop="incomeType">
              <el-radio-group v-model="form.incomeType">
                <el-radio v-for="dict in income_type" :key="dict.value"
                  :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="分成金额" prop="divideAmount">
              <el-input v-model="form.divideAmount" placeholder="请输入分成金额" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="云商到账金额" prop="protoAmount">
              <el-input v-model="form.protoAmount" placeholder="请输入云商到账金额" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="钱包类型" prop="walletType">
              <el-radio-group v-model="form.walletType">
                <el-radio v-for="dict in wallet_type" :key="dict.value"
                  :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="分润比例" prop="ratio">
              <el-input v-model="form.ratio" placeholder="请输入分润比例" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="云商收益编号" prop="earningsId">
              <el-input v-model="form.earningsId" placeholder="请输入云商收益编号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bill">
import { listBill, getBill, delBill, addBill, updateBill } from "@/api/finance/bill"

const { proxy } = getCurrentInstance()
const { wallet_type, change_type, income_type } = proxy.useDict('wallet_type', 'change_type', 'income_type')

const billList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const createTime = ref([])

// 列显隐信息
const columns = ref([
  { key: 0, label: `所属代理商`, visible: true },
  { key: 1, label: `订单号`, visible: true },
  { key: 2, label: `余额`, visible: true },
  { key: 3, label: `变动前金额`, visible: true },
  { key: 4, label: `变动后金额`, visible: true },
  { key: 5, label: `变动类型`, visible: true },
  { key: 6, label: `收益类型`, visible: true },
  { key: 7, label: `分成金额`, visible: true },
  { key: 8, label: `云商到账金额`, visible: true },
  { key: 9, label: `钱包类型`, visible: true },
  { key: 10, label: `分润比例`, visible: true },
  { key: 11, label: `创建时间`, visible: true },
  { key: 12, label: `设备MAC`, visible: true },

])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    agentName: null,
    orderNum: null,
    mac: null,
    changeType: null,
    incomeType: null,
    walletType: null,
    createTime: null,
  },
  rules: {
    agentName: [
      { required: true, message: "所属代理商不能为空", trigger: "blur" }
    ],
    orderNum: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "余额不能为空", trigger: "blur" }
    ],
    beforeAmount: [
      { required: true, message: "变动前金额不能为空", trigger: "blur" }
    ],
    afterAmount: [
      { required: true, message: "变动后金额不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询账户订单列表 */
function getList() {
  loading.value = true
  listBill(proxy.addDateRange(queryParams.value, createTime.value)).then(response => {
    billList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    agentId: null,
    orderNum: null,
    amount: null,
    beforeAmount: null,
    afterAmount: null,
    changeType: null,
    incomeType: null,
    divideAmount: null,
    protoAmount: null,
    walletType: null,
    ratio: null,
    earningsId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  
  proxy.resetForm("billRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 手动重置查询参数
  queryParams.value.agentName = null
  queryParams.value.orderNum = null
  queryParams.value.mac = null
  queryParams.value.changeType = null
  queryParams.value.incomeType = null
  queryParams.value.walletType = null
  queryParams.value.createTime = null
  createTime.value = []
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加账户订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBill(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改账户订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["billRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBill(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBill(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除账户订单编号为"' + _ids + '"的数据项？').then(function() {
    return delBill(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('finance/bill/export', {
    ...queryParams.value
  }, `bill_${new Date().getTime()}.xlsx`)
}

getList()

/** 动态计算字段数 **/
const fieldCount = ref(0)

onMounted(() => {
  // 统计表单字段数量
  fieldCount.value = [
    "agentId",
    "orderNum",
    "amount",
    "beforeAmount",
    "afterAmount",
    "changeType",
    "incomeType",
    "divideAmount",
    "protoAmount",
    "walletType",
    "ratio",
    "earningsId",
  ].length
})

const isTwoColumnForm = computed(() => fieldCount.value > 8)
const dialogWidth = computed(() => isTwoColumnForm.value ? '60vw' : '500px')
</script>
